#!/bin/sh

# redports dispatcher hook script

# Environment variables:
#   RPACTION
#   RPOWNER
#   RPSTATUS
#   RPBUILDID
#   RPBUILDQUEUEID
#   RPBUILDGROUP
#   RPPORTNAME
#   RPPKGVERSION
#   RPBUILDSTATUS
#   RPBUILDREASON
#   RPBUILDLOG
#   RPBACKENDHOST

MSG=""

case "${RPACTION}" in
    "BUILD_STARTED")
	MSG="[%02${RPBUILDGROUP}%0f] (${RPOWNER}) - ${RPPORTNAME} - start"
	;;

    "BUILD_FINISHED")
	MSG="[%02${RPBUILDGROUP}%0f] (${RPOWNER}) - ${RPPORTNAME} ${RPPKGVERSION}"
	case ${RPBUILDSTATUS} in
	    SUCCESS)
		MSG="${MSG} - %0303${RPBUILDSTATUS}%0f ${RPBUILDREASON}"
		;;
	    LEFTOVERS)
		MSG="${MSG} - %0306${RPBUILDSTATUS}%0f ${RPBUILDREASON}"
		;;
	    *)
		MSG="${MSG} - %0304${RPBUILDSTATUS}%0f ${RPBUILDREASON}"
		;;
	esac
	if [ ! -z "${RPBUILDLOG}" -a ${RPBUILDSTATUS} != "SUCCESS" ] ; then
	    MSG="${MSG} - ${RPWWWURL}/~${RPOWNER}/${RPBUILDQUEUEID}-${RPBUILDID}/${RPBUILDLOG}"
	fi
	;;

    "BACKENDBUILD_FAILED")
	MSG="[%02%0304ERROR%0f] Buildgroup %0304${RPBUILDGROUP}%0f on %0304${RPBACKENDHOST}%0f marked as failed! (call: decke mat_)"
	PROWLMSG="${RPBUILDGROUP} on ${RPBACKENDHOST} failed"
	;;

    "BACKEND_FAILED")
	MSG="[%02%0304ERROR%0f] Backend %0304${RPBACKENDHOST}%0f marked as failed! (call: decke mat_)"
	PROWLMSG="${RPBACKENDHOST} failed"
	;;
esac

if [ ! -z "${MSG}" ]; then
    echo ${MSG} >> /var/log/rpdd-hook.log
    fetch -q -o /dev/null "https://redportsircbot-bluelife.rhcloud.com/?token=TOKEN&msg=${MSG}"
fi

if [ ! -z "${PROWLMSG}" ]
then
    /usr/local/bin/curl https://api.prowlapp.com/publicapi/add \
	-F apikey=APIKEY1,APIKEY2 \
	-F priority=0 \
	-F application="Redports" \
	-F event="${RPACTION}" \
	-F description="${PROWLMSG}"
fi

exit 0

